package progress.exa29_3.ui;

import java.io.FileOutputStream;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.net.ServerSocket;
import java.net.Socket;

public class StudentServer {
    private ObjectOutputStream outputFile;//声明输出流
    private ObjectInputStream inputFromClient;//声明输入流

    public static void main(String[] args) {
        new StudentServer();
    }

    public StudentServer(){
        try {
            ServerSocket serverSocket = new ServerSocket(8001);//设置服务器端口为8001
            System.out.println("服务器已启动");
            //输出对象流到文件student.dat（在根目录）中
            outputFile = new ObjectOutputStream(new FileOutputStream("student.dat",true));
            while(true) {
                //进入监听状态
                Socket socket=serverSocket.accept();
                //实例化套接字对象输入流
                inputFromClient=new ObjectInputStream(socket.getInputStream());
                //定义object存放输入流对象信息
                Object object = inputFromClient.readObject();
                //将信息写入文件student.dat
                outputFile.writeObject(object);
                System.out.println("接收到一个Student数据: "+object.toString());
            }
        }catch (ClassNotFoundException ex){
            ex.printStackTrace();
        }catch (IOException ex) {
            ex.printStackTrace();
        } finally{
            try{
                inputFromClient.close();
                outputFile.close();
            }catch(Exception ex) {
                ex.printStackTrace();
            }
        }
    }

}